import {defineStore} from "pinia";
import {Tab} from "@/interface/tab";
import router from "@/router";

const useTabStore = defineStore('tab', {
  //定义状态：一个函数，返回一个对象
  state: () => {
    return {
      list: <Tab[]>[{title: '首页', path: '/dashboard', closable: false}], //tab列表
    }
  },
  //定义getters，等同于组建的计算属性
  getters: {
    //getter 函数接收 state 作为参数，推荐使用箭头函数
    // list: state => state.list

  },
  //定义actions，有同步和异步两种类型
  actions: {
    //异步action，一般用来处理异步逻辑
    //同步action
    get(){

    },
    async push(tab: Tab){
      if(this.list.every(item => item.path !== tab.path)){
        if(tab.path === '/auth/login'){
          return
        }
        this.list.push(tab)
      }
    },
    async remove(path: string, isCurrent: boolean = true)  {
      //删除当前标签，自动切换到下一个标签
      if(isCurrent){
        this.list.forEach((item:Tab, index:number) => {
          if(item.path!== path) return

          let nextTab = this.list[index+1] || this.list[index - 1]
          if(!nextTab) {
            return
          }else{
            router.push({path: nextTab.path})
          }
        })
      }

      this.list = this.list.filter(item => item.path !== path)
    },
    flush(){
      this.list = []
    }
  }

})
export default useTabStore